Insertion sort of linked list¶
Time: O(N^2); Space: O(1); medium
Sort a linked list using insertion sort
The partial sorted list (black) initially contains only the first element in the list. With each iteration one element (red) is removed from the input data
and inserted in-place into the sorted list.
Example 1:
Input: linked-list: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: linked-list: -1->5->3->4->0
Output: -1->0->3->4->5
1. Insertion Sort¶
Algorithm
Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
It repeats until no input elements remain.
[1]:
class ListNode:
"""
Singly-linked list
"""
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, repr(self.next))
else:
return None
class Solution1(object):
def insertionSortList(self, head):
'''
:type head: ListNode
:rtype: ListNode
'''
if head is None or self.isSorted(head):
return head
dummy = ListNode(-2147483648)
dummy.next = head
cur, sorted_tail = head.next, head
while cur:
prev = dummy
while prev.next.val < cur.val:
prev = prev.next
if prev == sorted_tail:
cur, sorted_tail = cur.next, cur
else:
cur.next, prev.next, sorted_tail.next = prev.next, cur, cur.next
cur = sorted_tail.next
return dummy.next
def isSorted(self, head):
while head and head.next:
if head.val > head.next.val:
return False
head = head.next
return True
[4]:
s = Solution1()
head = ListNode(4)
head.next = ListNode(2)
head.next.next = ListNode(1)
head.next.next.next = ListNode(3)
print(s.insertionSortList(head))
head = ListNode(-1)
head.next = ListNode(5)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(0)
print(s.insertionSortList(head))
1 -> 2 -> 3 -> 4 -> None
-1 -> 0 -> 3 -> 4 -> 5 -> None